package com.aube.plugin.detail;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aube.plugin.origin.R;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.IPositionManager;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.CategorySimple;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.Utils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/6/12.
 */
public class WidgetDesc extends DLLayout {

    //友盟统计点击人物简介/点击简介/人物名
    private static final String SEE_CHARACTER_DESC = "SEE_CHARACTER_DESC";

    private IPositionManager mManager;
    private AtomicBoolean mAnimated = new AtomicBoolean(false);

    private LinearLayout mLayoutGroup;
    private View mFlag, mHeadLayout;
    private TextView mTitle, mMore;
    private ImageView mArrow;

    private EllipsizingTextView mTxtInfo;

    private static final int ANIM_DURATION = 300;
    private static final int ANIM_DELAY = 200;

    private CategorySimple mCate;

    private String info;

    private int basicIntroLineCount = 0;
    private boolean isExpand = false;
    private AtomicBoolean mAnimating = new AtomicBoolean(false);

    public WidgetDesc(Context context) {
        this(context, null);
    }
    public WidgetDesc(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public WidgetDesc(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    public void initViews() {
        inflate(R.layout.widget_info, this, true);
        mLayoutGroup = (LinearLayout) findViewById(R.id.info_widget_group);

        mFlag = findViewById(R.id.header_flag);
        mTitle = (TextView) findViewById(R.id.header_widget_title);
        mMore = (TextView) findViewById(R.id.header_widget_more);
        mHeadLayout = findViewById(R.id.header_widget_layout);

        mArrow = (ImageView) findViewById(R.id.header_widget_arrow);
        mArrow.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_rightarrow));

        mFlag.setAlpha(0f);
        mTitle.setAlpha(0f);
        mMore.setAlpha(0f);
        mArrow.setAlpha(0f);
        mLayoutGroup.setAlpha(0f);
    }

    @Override
    public void fillData(Object object) {
        if(object == null || !(object instanceof Category)) {
            Utils.sysout("***********************object is null:" + (object == null));
            return;
        }
        Category category = (Category) object;
        mCate = category.getSimpleCategory();

        mTitle.setText(category.modelName);
        if(StringUtils.isNotBlank(category.modelDesc)) {
            mMore.setText(category.modelDesc);
            mHeadLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    expandView();
                }
            });
        } else {
            mMore.setVisibility(View.GONE);
            mArrow.setVisibility(View.GONE);
        }

        Utils.sysout("***********************widgetdesc");
        List list = (List) category.dataDetail;
        for(Object obj : list) {
            LinkedHashMap<String, Object> lhm = (LinkedHashMap<String, Object>) obj;
            String content = (String) lhm.get("content");
            Utils.sysout("***********************widgetdesc:" + content);
            fillContent(content);
            return;
        }
    }

    private void fillContent(String intro) {
        if(StringUtils.isBlank(intro))
            return;
        info = intro;//.replace("\n", "");
        mTxtInfo = new EllipsizingTextView(context);
        mLayoutGroup.addView(mTxtInfo, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        mTxtInfo.setTextSize(14);
        mTxtInfo.setTextColor(Color.WHITE);
        mTxtInfo.setLineSpacing(5, 1.1f);
        mTxtInfo.setReadUp(false);
        mTxtInfo.setText(info);
        basicIntroLineCount = mTxtInfo.getLineCount();
        mTxtInfo.setMaxLines(2);
        mTxtInfo.setOnClickListener(basicIntroListener);
    }

    private View.OnClickListener basicIntroListener = new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            expandView();
        }
    };

    public void expandView() {
        if(mAnimating.get())
            return;
        mAnimating.set(true);
        //必须
        mTxtInfo.setText(info);
        if(!isExpand) {
            mTxtInfo.setMaxLines(Integer.MAX_VALUE); //展开的时候不设置maxline，显示完整数据
            if (basicIntroLineCount == 0) {
                basicIntroLineCount = mTxtInfo.getLineCount();
            }
            expandTextViewWithAnim(2, basicIntroLineCount, new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mAnimating.set(false);
                }
            });
            isExpand = true;

            if(mBridge != null)
                mBridge.reportUmengEvent(SEE_CHARACTER_DESC, mCate.relatedId);
        } else {
            expandTextViewWithAnim(basicIntroLineCount, 2, new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mAnimating.set(false);
                    mTxtInfo.setMaxLines(2);
                }
            });
            isExpand = false;
        }
    }

    public void expandTextViewWithAnim(int fromLineCount,int toLineCount, Animator.AnimatorListener listener){
        int lineHeight = mTxtInfo.getLineHeight();
        ValueAnimator anim = ValueAnimator.ofInt(fromLineCount * lineHeight, toLineCount * lineHeight);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int cVal = (int) animation.getAnimatedValue();
                ViewGroup.LayoutParams lp = mTxtInfo.getLayoutParams();
                lp.height = cVal;
                mTxtInfo.setLayoutParams(lp);
            }
        });
        if(listener != null)
            anim.addListener(listener);
        anim.setDuration(300);
        anim.start();
    }

    public void setTheme(int color) {
        mFlag.setBackgroundColor(color);
    }

    @Override
    public void notifyAnim(int animDelay) {
        if(mManager == null)
            return;
        if(mAnimated.get())
            return;
        mAnimated.set(true);
        mLayoutGroup.setVisibility(View.VISIBLE);
        if(animDelay > 0)
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    anim();
                }
            }, animDelay);
        else
            anim();
    }

    private void anim() {
        ObjectAnimator alphaTitle = ObjectAnimator.ofFloat(mTitle, "alpha", 0, 1);
        alphaTitle.setDuration(ANIM_DURATION);

        ObjectAnimator alphaDes = ObjectAnimator.ofFloat(mMore, "alpha", 0, 1);
        alphaDes.setDuration(ANIM_DURATION);
        alphaDes.setStartDelay(ANIM_DELAY);

        ObjectAnimator alphaArrow = ObjectAnimator.ofFloat(mArrow, "alpha", 0, 1);
        alphaArrow.setDuration(ANIM_DURATION);
        alphaArrow.setStartDelay(ANIM_DELAY);

        ObjectAnimator translate = ObjectAnimator.ofFloat(mFlag, "translationY", -mFlag.getHeight(), 0);
        translate.setDuration(ANIM_DURATION);
        translate.setStartDelay(ANIM_DELAY);
        translate.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mFlag.setAlpha(1f);
            }
        });

        ObjectAnimator alphaGroup = ObjectAnimator.ofFloat(mLayoutGroup, "alpha", 0, 1);
        alphaGroup.setDuration(ANIM_DURATION);
        alphaGroup.setStartDelay(ANIM_DELAY*2);

        AnimatorSet mSet = new AnimatorSet();
        mSet.playTogether(alphaTitle, alphaDes, alphaArrow, translate, alphaGroup);
        mSet.start();
    }

    @Override
    public void registToManager(IPositionManager manager) {
        if(mManager != null || manager == null)
            return;
        manager.add(this);
        this.mManager = manager;

        mLayoutGroup.setVisibility(View.INVISIBLE);
    }

    @Override
    public void unreistFromManager(IPositionManager manager) {
        if(mManager == null || manager == null)
            return;
        manager.remove(this);
        this.mManager = null;
    }

    @Override
    public int[] getLocations() {
        int[] locs = new int[2];
        getLocationOnScreen(locs);
        return locs;
    }
}
